'use strict';


var BBSContract = function () {
    LocalContractStorage.defineMapProperty(this, "playerPlayRecordsMap");
    LocalContractStorage.defineMapProperty(this, "orderedRanklist");
    LocalContractStorage.defineMapProperty(this, "playerHighestScoreRecordMap");
};

BBSContract.prototype = {
    init: function () {
    },
    //存储游戏结果
    storePlayResult: function (newScore) {
        try {
            console.log(typeof(newScore))
            newScore = parseInt(newScore)
            console.log("after " + typeof(newScore))
            var fromUser = Blockchain.transaction.from,
                ts = Blockchain.transaction.timestamp;
            var newRecord = {
                playTime: ts,
                score: parseInt(newScore)
            }
            var isBreakOwnRecord = false;

            var str = this.playerPlayRecordsMap.get(fromUser);
            if (str) {
                var recordObject = JSON.parse(str);
                console.log("old ...size :" + recordObject.recordArray.length)
                //将新游戏记录，加入数组
                recordObject.recordArray.push(newRecord)
                console.log("new ...size :" + recordObject.recordArray.length)

                var stringify = JSON.stringify(recordObject);
                this.playerPlayRecordsMap.set(fromUser, stringify);

                //判断是否破了自己记录
                var highScoreRecord = JSON.parse(this.playerHighestScoreRecordMap.get(fromUser));
                //设置是否破自己记录标志
                if (highScoreRecord.score < newScore) {
                    isBreakOwnRecord = true;
                }
            } else {
                console.log("new ...")

                var initialRecords = [];
                initialRecords.push(newRecord)
                var recordObect = {
                    recordArray: initialRecords
                }
                //第一条游戏记录
                var playRecord = JSON.stringify(recordObect);
                this.playerPlayRecordsMap.set(fromUser, playRecord);

                isBreakOwnRecord = true;
                console.log("49:" + playRecord)
            }

            //设置自己的最高记录
            if (isBreakOwnRecord) {
                this.playerHighestScoreRecordMap.set(fromUser, JSON.stringify(newRecord))
            }
            var playerPlayRecordsStr = this.playerPlayRecordsMap.get(fromUser);
            console.log(playerPlayRecordsStr)
            console.log("isBreakOwnRecord: " + isBreakOwnRecord)

            //破了自己记录的话，将成绩上榜,与其他人进行pk;没破自己记录的话（榜单上肯定有数据，但是没超过之前的最高成绩），
            // 不需要处理
            if (isBreakOwnRecord) {
                var ranklistItem = {
                    userAddress: fromUser,
                    score: newScore,
                    playTime: ts
                };
                var rankArrayStr = this.orderedRanklist.get("stub");
                if (rankArrayStr) {
                    console.log("61: ", rankArrayStr);

                    var rankArray = JSON.parse(rankArrayStr);
                    //查找榜单上是否已存在自己的成绩
                    var filteredItem = null;
                    for (var i = 0; i < rankArray.length; i++) {
                        var item = rankArray[i];
                        if (item.userAddress == fromUser) {
                            filteredItem = item;
                            break;
                        }
                    }
                    //存在的话，直接修改为当前的记录
                    if (filteredItem) {
                        console.log("modify old :" + filteredItem)
                        filteredItem.score = newScore;
                        filteredItem.playTime = ts;
                    } else {
                        //加入榜单
                        rankArray.push(ranklistItem)
                    }
                    //排序
                    rankArray = rankArray.sort(function (p, n) {
                        return n.score > p.score
                    })
                    //排序后的数组，放回排行榜map对象中。
                    this.orderedRanklist.set("stub", JSON.stringify(rankArray));
                } else {
                    //排行榜无数据
                    var rankArray = [];
                    //加入榜单
                    rankArray.push(ranklistItem)
                    //存储榜单
                    this.orderedRanklist.set("stub", JSON.stringify(rankArray));
                }

                console.log("ranklist: " + JSON.parse(this.orderedRanklist.get("stub")));
            }
        } catch (err) {
            throw  err;
        }

    },
    //获取个人游戏记录
    getPlayerRecords: function (userAddress) {
        console.log("81" + userAddress)
        console.log("81" + typeof(userAddress))
        var playerPlayRecordsStr = this.playerPlayRecordsMap.get(userAddress);
        console.log(playerPlayRecordsStr)
        if (playerPlayRecordsStr) {
            return JSON.parse(playerPlayRecordsStr).recordArray
        }
        //用户无记录
        throw new Error("10010")
    },
    //获取玩家最高记录
    getHighestPlayerRecord: function (userAddress) {
        var highScoreRecord = JSON.parse(this.playerHighestScoreRecordMap.get(userAddress));
        if (highScoreRecord) {
            return highScoreRecord
        }
        //用户无记录
        throw new Error("10010")
    },
    //获取排行榜
    getRankList: function (userAddress) {
        console.log("141 " + userAddress)
        var arrayStr = this.orderedRanklist.get("stub");
        var array = JSON.parse(arrayStr);
        console.log("size:" + array.length)
        var rankOfUser = null;
        for (var i = 0; i < array.length; i++) {
            console.log(array[i])
            console.log(array[i].userAddress)
            if (array[i].userAddress == userAddress) {
                rankOfUser = i;
                break;
            }
            console.log("come: " + JSON.stringify(array[i]));
        }

        return {rankList: array, userRank: i + 1};
    }
};

module.exports = BBSContract;